/*
 * @Author: wangtao
 * @Date: 2021-01-14 16:00:34
 * @LastEditors: zeki mini
 * @LastEditTime: 2021-04-14 13:59:48
 * @Description: file content
 */
import React, { Component } from 'react';
import {
  StyleSheet,
  View,
  BackHandler,
  SafeAreaView,
  NativeModules,
  DeviceEventEmitter,
  NativeEventEmitter,
  Platform,
} from 'react-native';
import AsyncStorage from '@react-native-community/async-storage';
import {
  isAndroid,
  mainBgColorLightGray,
  mainBgColorWhite,
} from '../../../../common/styles/index';
import { msg, _, cache } from '../../../../common';
import SelectAddressHeader from './components/select-address-header';
import CurrentPosition from './components/current-position';
import AddressHistory from './components/address-history';
import AddressSearchList from './components/address-search-list';

export default class ReleaseSourceSelectAddress extends Component {
  constructor(props) {
    super(props);
    this.state = {
      currentPosition: {}, // 当前定位
      addressSeachKey: '', // 地址搜索关键字
      addressSearchList: [], // 地址搜索
      addressSearchHistoryList: [], // 地址搜索历史
      isSearch: false, // 正在搜索
      searchProcess: 'searchProcesswill', // searchProcesswill  searchProcessing  searchProcessed
      type: 1, // 装卸货
      sort: 0, // 装卸货排序
    };
  }

  componentDidMount() {
    // 处理安卓物理返回键
    if (Platform.OS == 'android') {
      BackHandler.addEventListener('hardwareBackPress', this.onBackAndroid);
    }
    const { navigation } = this.props;
    const state = navigation.state || {};
    const params = state.params || {};
    const { type, sort } = params;
    this.setState({ type, sort });
    // 获取当前位置
    this.getCurrentPosition();
    // android百度联想api 注册
    NativeModules.MapModule.registerSuggestionListener();
    // 地图确认检测
    if (isAndroid) {
      this.mapPositionListener = DeviceEventEmitter.addListener(
        'map_position',
        (str) => {
          const { province, city, area, street, lon, lat, name } = JSON.parse(str);
          console.log('🚀🚀🚀wimi======>>>JSON.parse(str)', JSON.parse(str));
          // this.setState({ addressValue: `${street}`, province, city, area, });
          msg.emit('selectAddress', {
            province,
            city,
            district: area,
            addressDetails: name,
            lgt: lon,
            lat,
            name,
            type,
            sort,
          });
          msg.emit('router: goToNext', {
            routeName: 'ReleaseSource',
          });
        },
      );
    } else {
      this.mapListenerIOS(type, sort);
    }

    // 搜索历史
    AsyncStorage.getItem(cache.ADDRESS_SEARCH_LIST_RELEASE_SOURCE).then(
      (res) => {
        console.log('🚀🚀🚀wimi======>>>addressSearchHistoryList', res);
        const addressSearchHistoryList = JSON.parse(res);
        if (addressSearchHistoryList) {
          this.setState({ addressSearchHistoryList });
        } else {
          this.setState({ addressSearchHistoryList: [] });
        }
      },
    );
  }

  componentWillUnmount() {
    NativeModules.MapModule.unregisterSuggestionListener(); // 百度检索联想 api 销毁
    this.mapPositionListener.remove(); // 地图选址销毁
    if (Platform.OS === 'android') {
      BackHandler.removeEventListener('hardwareBackPress', this.onBackAndroid);
    }
  }

  onBackAndroid = () => {
    msg.emit('router: back');
    return true;
  };

  render() {
    const {
      currentPosition,
      addressSearchList,
      searchProcess,
      addressSearchHistoryList,
    } = this.state;
    return (
      <SafeAreaView style={{ flex: 1, backgroundColor: mainBgColorWhite }}>
        <View style={{ flex: 1, backgroundColor: mainBgColorLightGray }}>
          {/* 选择地址 */}
          <SelectAddressHeader changeAddress={this.changeAddress} />
          {/* 当前点 */}
          {searchProcess === 'searchProcesswill' && (
            <CurrentPosition
              currentPosition={currentPosition}
              selectMapPosition={this.selectMapPosition}
            />
          )}
          {/* 历史记录 */}
          {searchProcess === 'searchProcesswill' &&
            !!addressSearchHistoryList.length && (
            <AddressHistory
              addressSearchHistoryList={addressSearchHistoryList}
              selectMapPosition={this.selectMapPosition}
              onChange={this.onChange}
            />
          )}
          {/* 正在搜索 */}
          {searchProcess === 'searchProcessed' && (
            <AddressSearchList
              addressSearchList={addressSearchList}
              selectMapPosition={this.selectMapPosition}
            />
          )}
        </View>
      </SafeAreaView>
    );
  }

  // ios地图选点回调监听
  mapListenerIOS = (type, sort) => {
    const { GJCommonEmitter } = NativeModules;
    const calendarManagerEmitter = new NativeEventEmitter(GJCommonEmitter);
    this.mapPositionListener = calendarManagerEmitter.addListener(
      'map_position',
      (str) => {
        const { province, city, area, street, lon, lat, name } = JSON.parse(str);
        msg.emit('selectAddress', {
          province,
          city,
          district: area,
          addressDetails: name,
          lgt: lon,
          lat,
          name,
          type,
          sort,
        });
        msg.emit('router: goToNext', {
          routeName: 'ReleaseSource',
        });
      },
    );
  };

  // 输入关键字
  changeAddress = (addressSeachKey) => {
    // 调接口 联想地址,将地址push addressSearchList
    this.setState({ addressSeachKey, searchProcess: 'searchProcesswill' });
    NativeModules.MapModule.suggestionSearch(
      { keyword: addressSeachKey, city: '' },
      (data) => {
        this.setState({
          addressSeachKey,
          addressSearchList: data ? JSON.parse(data) : [],
          searchProcess: 'searchProcessed',
        });
      },
    );
  };

  // 获取当前定位
  getCurrentPosition = () => {
    // 当前定位
    NativeModules.MapModule.getCurrentPosition().then((resPosition) => {
      console.log('🚀🚀🚀wimi======>>>resPosition', resPosition);
      resPosition.area = resPosition.district;
      if (resPosition.city !== null && resPosition.city !== undefined) {
        this.setState({ currentPosition: resPosition });
      } else {
        msg.emit('app:tip', { text: '获取地理位置信息失败' });
      }
    });
  };

  // 跳转
  selectMapPosition = (addressInfo) => {
    console.log('🚀🚀🚀wimi======>>>addressInfo', addressInfo);
    this.setSearchHistory(addressInfo);
    const { province, city, area, longitude, latitude } = addressInfo;
    const { type } = this.state;
    let pointType = '';
    if (type === 1) {
      pointType = '装货点';
    } else {
      pointType = '卸货点';
    }
    NativeModules.BridgeManager.startRouteActivity(
      `xmgj://normal.com/app/goods/choose_address?type=${pointType}&province=${province}&city=${city}&area=${area}&lon=${longitude}&lat=${latitude}`,
    );
  };

  // 存储历史记录
  setSearchHistory = (addressInfo) => {
    console.log('🚀🚀🚀wimi======>>>addressInfo', addressInfo);
    AsyncStorage.getItem(cache.ADDRESS_SEARCH_LIST_RELEASE_SOURCE).then(
      (res) => {
        let list = JSON.parse(res);
        if (!list) {
          [].push(addressInfo);
        } else {
          list = list.filter(item => {
            if (item.street != addressInfo.street) {
              return true;
            }
          });
          list.push(addressInfo);
        }

        AsyncStorage.setItem(
          cache.ADDRESS_SEARCH_LIST_RELEASE_SOURCE,
          JSON.stringify(list),
        );
      },
    );
  };

  //
  onChange = (key, val) => {
    this.setState({
      [key]: val
    });
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
});
